package com.lp.multi.thread.example05;

/**
 * @author: lp
 * @create: 2021-06-22 11:33
 * @description: 并发不安全案例2，银行取钱
 */
public class SafeBankThreadTest {
    public static void main(String[] args) {
        Account2 account = new Account2();
        account.setAccountNo("100000");
        account.setMoney(100);

        BankThread2 thread = new BankThread2(account,50,"我");
        BankThread2 thread2 = new BankThread2(account,70,"媳妇");

        new Thread(thread).start();
        new Thread(thread2).start();




    }

}

class Account2{
    private String accountNo;
    private int money;

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}

class BankThread2 extends Thread{
    private Account2 account;
    private int withdrawMoney;

    public BankThread2(Account2 account,int withdrawMoney,String threadName){
        this.setName(threadName);
        this.account = account;
        this.withdrawMoney = withdrawMoney;
    }

    @Override
    public void run() {
        //锁住变化的共享对象
        synchronized (account){
            if(account.getMoney() < withdrawMoney){
                System.out.println(this.getName()+"取款失败，当前金额为:"+ account.getMoney()+",申请取款金额为:"+withdrawMoney);
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.setMoney(account.getMoney()-withdrawMoney);
            System.out.println(this.getName()+"取款成功，当前剩余金额为:"+ account.getMoney()+",本次取款金额为:"+withdrawMoney);
        }

    }
}
